package com.cx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cx.common.R;
import com.cx.common.ServiceException;
import com.cx.mapper.UserMapper;
import com.cx.pojo.vo.UserVo;
import com.cx.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserVo>  {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 设置过期时间
     */
    private final static Long EXPIRE=(long)3600 * 24;


    public R LoginIn(UserVo userVo){
        UserVo userVo1 = baseMapper.selectOne(new QueryWrapper<UserVo>().eq("userName", userVo.getUserName())
                .eq("passWord", userVo.getPassWord()));

        if(userVo1==null){

            throw new ServiceException("记录不存在");
        }else {

            String token = UUID.randomUUID().toString().replace("-", "");
            redisUtil.setString(token,userVo.getId().toString(),EXPIRE);

            HashMap<Object, Object> map = new HashMap();
            map.put("token",token);
            map.put("userName",userVo.getUserName());
            map.put("id",userVo.getId());

            return R.ok();
        }
    }

    public R LoginOut(HttpServletRequest httpServletRequest){
        String header = httpServletRequest.getHeader("Token");

        redisUtil.delKey(header);

        return R.ok();
    }
}
